<template>
	<section>
		<!--工具条-->
		<el-col :span="24" class="toolbar" style="padding-bottom: 0px;">
			<el-form :inline="true" :model="filters">
				<el-form-item>
					<el-input v-model="filters.name" placeholder="姓名"></el-input>
				</el-form-item>
				<el-form-item>
					<el-button type="primary" v-on:click="getUsers">查询</el-button>
				</el-form-item>
				<el-form-item>
					<el-button type="primary" @click="handleAdd">新增</el-button>
				</el-form-item>
				<el-form-item>
					<el-button type="primary" @click="syncUser">同步用户</el-button>
				</el-form-item>
			</el-form>
		</el-col>

		<!--列表-->
		<el-table :data="users" highlight-current-row v-loading="listLoading" @selection-change="selsChange" style="width: 100%;">
			<el-table-column type="index" width="60">
			</el-table-column>
			<el-table-column label="头像" width="150">
				<template scope="scope">
					<img class='user-list-avatar' :src="scope.row.avatar"/>
				</template>
			</el-table-column>
			<el-table-column prop="username" label="用户名" width="200" sortable>
			</el-table-column>
			<el-table-column prop="nickname" label="昵称" width="200" sortable>
			</el-table-column>
			<el-table-column prop="login_ip" label="最后登陆IP" width="150" >
			</el-table-column>
			<el-table-column prop="created_time" label="创建时间" width="200" sortable>
			</el-table-column>

			<el-table-column label="操作" width="260">
				<template scope="scope">
					<el-button size="small" @click="handleEdit(scope.$index, scope.row)">编辑</el-button>
					<el-button size="small" @click="handleChangePas(scope.$index, scope.row)">修改密码</el-button>
					<el-button type="danger" size="small" @click="handleDel(scope.$index, scope.row)">删除</el-button>
				</template>
			</el-table-column>
		</el-table>

		<!--编辑界面-->
		<el-dialog title="编辑" v-model="editFormVisible" :close-on-click-modal="false">
			<el-form :model="editForm" label-width="80px" :rules="editFormRules" ref="editForm">
				<el-form-item label="用户名" prop="username">
					<el-input v-model="editForm.username" auto-complete="off"></el-input>
				</el-form-item>
				<el-form-item label="昵称" prop="nickname">
					<el-input v-model="editForm.nickname" auto-complete="off"></el-input>
				</el-form-item>
			</el-form>
			<div slot="footer" class="dialog-footer">
				<el-button @click.native="editFormVisible = false">取消</el-button>
				<el-button type="primary" @click.native="editSubmit" :loading="editLoading">提交</el-button>
			</div>
		</el-dialog>

		<!--新增界面-->
		<el-dialog title="新增" v-model="addFormVisible" :close-on-click-modal="false">
			<el-form :model="addForm" label-width="80px" :rules="addFormRules" ref="addForm">
				<el-form-item label="头像" prop="avatar">
				<el-upload
						class="avatar-uploader"
						action=""
						:http-request="upLoad"
						:show-file-list="false"
						:on-success="handleAvatarSuccess"
						:before-upload="beforeAvatarUpload">
					<img v-if="addForm.avatar" :src="addForm.avatar" class="avatar">
					<i v-else class="el-icon-plus avatar-uploader-icon"></i>
				</el-upload>
				</el-form-item>
				<el-form-item label="用户名" prop="username">
					<el-input v-model="addForm.username" auto-complete="off"></el-input>
				</el-form-item>
				<el-form-item label="昵称" prop="nickname">
					<el-input v-model="addForm.nickname" auto-complete="off"></el-input>
				</el-form-item>
				<el-form-item label="密码" prop="password">
					<el-input
							:type="addForm.show.new?'text':'password'"
							v-model="addForm.password"
							placeholder="请输入密码"
					><img
								:src="addForm.show.new?'./image/show.png':'./image/hide.png'"
								slot="suffix"
								alt=""
								style="margin: 10px 0;"
								@click="addForm.show.new=!addForm.show.new"
						>
					</el-input>
				</el-form-item>
				<el-form-item label="确认密码" prop="checkPass">
					<el-input
							:type="addForm.show.check?'text':'password'"
							v-model="addForm.checkPass"
							placeholder="请确认密码"
					>
						<img
								:src="addForm.show.check?'./image/show.png':'./image/hide.png'"
								slot="suffix"
								alt=""
								style="margin: 10px 0;"
								@click="addForm.show.check=!addForm.show.check"
						>
					</el-input>
				</el-form-item>
			</el-form>
			<div slot="footer" class="dialog-footer">
				<el-button @click.native="addFormVisible = false">取消</el-button>
				<el-button type="primary" @click.native="addSubmit" :loading="addLoading">提交</el-button>
			</div>
		</el-dialog>

		<!-- 修改密码-->
		<el-dialog title="更改密码" v-model="changePasFormVisible" :close-on-click-modal="false">
			<el-form :model="changePasForm" label-width="80px" :rules="changePasFormRules" ref="changePasForm">
				<el-form-item label="密码" prop="pas">
					<el-input
							:type="changePasForm.show.new?'text':'password'"
							v-model="changePasForm.pas"
							placeholder="请输入密码"
					><img
							:src="changePasForm.show.new?'./image/show.png':'./image/hide.png'"
							slot="suffix"
							alt=""
							style="margin: 10px 0;"
							@click="changePasForm.show.new=!changePasForm.show.new"
					>
					</el-input>
				</el-form-item>
				<el-form-item label="确认密码" prop="checkPas">
					<el-input
							:type="changePasForm.show.check?'text':'password'"
							v-model="changePasForm.checkPas"
							placeholder="请确认密码"
					>
						<img
								:src="changePasForm.show.check?'./image/show.png':'./image/hide.png'"
								slot="suffix"
								alt=""
								style="margin: 10px 0;"
								@click="changePasForm.show.check=!changePasForm.show.check"
						>
					</el-input>
				</el-form-item>
			</el-form>
			<div slot="footer" class="dialog-footer">
				<el-button @click.native="changePasFormVisible = false">取消</el-button>
				<el-button type="primary" @click.native="changeSubmit" :loading="changePasLoading">提交</el-button>
			</div>
		</el-dialog>
	</section>
</template>

<script>
	import util from '../../common/js/util'
	//import NProgress from 'nprogress'
	import { base, getUserListPage, changPasswordUser, syncUser, removeUser, batchRemoveUser, editUser, addUser, uploadImage } from '../../api/api';

	export default {
		data() {
			var validatePass = (rule, value, callback) => {
				if (value === '') {
					callback(new Error('请输入密码'));
				} else {
					if (this.addForm.checkPass !== '') {
						this.$refs.addForm.validateField('checkPass');
					}
					callback();
				}
			};
			var validatePass2 = (rule, value, callback) => {
				if (value === '') {
					callback(new Error('请再次输入密码'));
				} else if (value !== this.addForm.password) {
					callback(new Error('两次输入密码不一致!'));
				} else {
					callback();
				}
			};
      var validatePass3 = (rule, value, callback) => {
        if (value === '') {
          callback(new Error('请输入密码'));
        } else {
          if (this.changePasFormRules.checkPas !== '') {
            this.$refs.changePasForm.validateField('checkPas');
          }
          callback();
        }
      };
      var validatePass4 = (rule, value, callback) => {
        if (value === '') {
          callback(new Error('请再次输入密码'));
        } else if (value !== this.changePasFormRules.pas) {
          callback(new Error('两次输入密码不一致!'));
        } else {
          callback();
        }
      };
			return {
				filters: {
					username: ''
				},
				users: [],
				total: 0,
				page: 1,
				listLoading: false,
				sels: [],//列表选中列

				editFormVisible: false,//编辑界面是否显示
				editLoading: false,
				editFormRules: {
					username: [
						{ required: true, message: '请输入用户名', trigger: 'blur' }
					],
					nickname: [
						{ required: true, message: '请输入昵称', trigger: 'blur' }
					]
				},
				//编辑界面数据
				editForm: {
					id: 0,
					username: '',
					nickname: -1,
				},

				changePasFormVisible: false,//编辑界面是否显示
				changePasLoading: false,
				changePasFormRules: {
					pas: [
						{ required: true, validator: validatePass3, trigger: 'blur' }
					],
					checkPas: [
						{ required: true, validator: validatePass4, trigger: 'blur' }
					],
				},
				//编辑界面数据
				changePasForm: {
					id: 0,
					pas: '',
					checkPas: '',
					show: {
						new:false,
						check: false,
					},
				},

				addFormVisible: false,//新增界面是否显示
				addLoading: false,
				addFormRules: {
					username: [
						{ required: true, message: '请输入用户名', trigger: 'blur' }
					],
					nickname: [
						{ required: true, message: '请输入昵称', trigger: 'blur' }
					],
					password: [
						{ required: true, validator: validatePass, trigger: 'blur' }
					],
					checkPass: [
						{ required: true, validator: validatePass2, trigger: 'blur' }
					],
				},
				//新增界面数据
				addForm: {
					username: '',
					nickname: '',
					password: null,
					checkPass: null,
					avatar: '',
					show: {
						new:false,
						check: false,
					},
				}

			}
		},
		methods: {
			handleCurrentChange(val) {
				this.page = val;
				this.getUsers();
			},
			//获取用户列表
			getUsers() {
				let para = {
					page: this.page,
					name: this.filters.name
				};
				this.listLoading = true;
				getUserListPage(para).then((res) => {
					console.log(res);
					this.total = res.data.total;
					this.users = res.data.users;
					this.listLoading = false;
				});
			},
			changeSubmit: function () {
				this.$refs.changePasForm.validate((valid) => {
					if (valid) {
						this.$confirm('确认提交吗？', '提示', {}).then(() => {
							this.changePasLoading = true;
							//NProgress.start();
							let para = Object.assign({}, this.changePasForm);
							var pasParams = { password: para.pas };

							changPasswordUser(para.id, pasParams).then((res) => {
								this.changePasLoading = false;
								//NProgress.done();
								this.$message({
									message: '提交成功',
									type: 'success'
								});
								this.$refs['changePasForm'].resetFields();
								this.changePasFormVisible = false;
								this.getUsers();
							});
						});
					}
				});
			},
			//删除
			handleDel: function (index, row) {
				this.$confirm('确认删除该记录吗?', '提示', {
					type: 'warning'
				}).then(() => {
					this.listLoading = true;
					//NProgress.start();
					removeUser(row.id).then((res) => {
						this.listLoading = false;
						//NProgress.done();
						this.$message({
							message: '删除成功',
							type: 'success'
						});
						this.getUsers();
					});
				}).catch(() => {

				});
			},
			syncUser: function () {
				syncUser().then((res) => {
					this.editLoading = false;
					//NProgress.done();
					this.$message({
						message: '同步成功',
						type: 'success'
					});
					this.getUsers();
				});
			},
			//显示编辑界面
			handleEdit: function (index, row) {
				this.editFormVisible = true;
				this.editForm = Object.assign({}, row);
			},
			handleChangePas: function (index, row) {
				this.changePasFormVisible = true;
				this.changePasForm = {
					id: row.id,
					pas: '',
					checkPas: '',
					show: {
						new:false,
						check: false,
					},
				};
			},
			//显示新增界面
			handleAdd: function () {
				this.addFormVisible = true;
				this.addForm = {
					username: '',
					nickname: '',
					password: null,
					checkPass: null,
					avatar: '',
					show: {
						new:false,
						check: false,
					},
				};
			},
			//编辑
			editSubmit: function () {
				this.$refs.editForm.validate((valid) => {
					if (valid) {
						this.$confirm('确认提交吗？', '提示', {}).then(() => {
							this.editLoading = true;
							//NProgress.start();
							let para = Object.assign({}, this.editForm);
							var editParams = { username: para.username, nickname: para.nickname };

							editUser(para.id, editParams).then((res) => {
								this.editLoading = false;
								//NProgress.done();
								this.$message({
									message: '提交成功',
									type: 'success'
								});
								this.$refs['editForm'].resetFields();
								this.editFormVisible = false;
								this.getUsers();
							});
						});
					}
				});
			},
			//新增
			addSubmit: function () {
				this.$refs.addForm.validate((valid) => {
					if (valid) {
						this.$confirm('确认提交吗？', '提示', {}).then(() => {
							this.addLoading = true;
							//NProgress.start();
							let para = Object.assign({}, this.addForm);
							addUser(para).then((res) => {
								this.addLoading = false;
								//NProgress.done();
								this.$message({
									message: '提交成功',
									type: 'success'
								});
								this.$refs['addForm'].resetFields();
								this.addFormVisible = false;
								this.getUsers();
							});
						});
					}
				});
			},
			handleAvatarSuccess(res, file) {
				this.addForm.avatar = URL.createObjectURL(file.raw);
			},
			beforeAvatarUpload(file) {
				const isJPG = file.type === 'image/jpeg';
				const isLt3M = file.size / 1024 / 1024 < 3;

				if (!isJPG) {
					this.$message.error('上传头像图片只能是 JPG 格式!');
				}
				if (!isLt3M) {
					this.$message.error('上传头像图片大小不能超过 3MB!');
				}
				return isJPG && isLt3M;
			},
			upLoad(file) {
				const formData = new FormData();
				formData.append('image', file.file);
				console.log(file);
				console.log(formData);
				uploadImage(formData).then((res) => {
					console.log(res);
					console.log('上传成功');
					console.log(base);
					if (res.data.code !== 500) {
						this.addForm.avatar = base+res.data.avatar; // 请求成功之后赋给头像的URL
						this.$message('头像上传成功');
					} else {
						this.$message('头像上传失败');
					}
				});
			},
			selsChange: function (sels) {
				this.sels = sels;
			},
			//批量删除
			batchRemove: function () {
				var ids = this.sels.map(item => item.id).toString();
				this.$confirm('确认删除选中记录吗？', '提示', {
					type: 'warning'
				}).then(() => {
					this.listLoading = true;
					//NProgress.start();
					let para = { ids: ids };
					batchRemoveUser(para).then((res) => {
						this.listLoading = false;
						//NProgress.done();
						this.$message({
							message: '删除成功',
							type: 'success'
						});
						this.getUsers();
					});
				}).catch(() => {

				});
			}
		},
		mounted() {
			this.getUsers();
		}
	}

</script>

<style scoped>
 .user-list-avatar {
	 width: 50px;
	 height: 50px;
	 border-radius:5px;
	 margin-top: 5px
 }
 .avatar-uploader .el-upload {
	 border: 1px dashed #d9d9d9;
	 border-radius: 6px;
	 cursor: pointer;
	 position: relative;
	 overflow: hidden;
 }
 .avatar-uploader .el-upload:hover {
	 border-color: #409EFF;
 }
 .avatar-uploader-icon {
	 font-size: 28px;
	 color: #8c939d;
	 width: 178px;
	 height: 178px;
	 line-height: 178px;
	 text-align: center;
 }
 .avatar {
	 width: 178px;
	 height: 178px;
	 display: block;
 }
</style>